//
//  SAMemberTopUpVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/28.
//

#import "SAMemberTopUpVC.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SASystemEmpSearchAPI.h"
#import "SAStoreUserModel.h"
#import "BubbleTableView.h"
#import "SAMemberRechargeAPI.h"
#import "SAMemberRechargePayAPI.h"
#import "SAReceiveQueryStatusAPI.h"
#import "GFAlertView.h"
#import "ScanHelper.h"
#import "SAGetPayPermissionAPI.h"
#import "SAPirntTopUpBillModel.h"

@interface SAMemberTopUpVC ()<HTTPAPIDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITextField *topUpTf;
@property (nonatomic, strong) UITextField *givingTf;
@property (nonatomic, strong) UITextField *empTf;
@property (nonatomic, strong) UITextField *typeTf;

@property (nonatomic, strong) UIButton *empBtn;
@property (nonatomic, strong) UIButton *typeBtn;

@property (nonatomic, strong) NSString *titleName;
@property (nonatomic, strong) NSString *memberId;
@property (nonatomic, strong) NSString *memberName;

@property (nonatomic, strong) SASystemEmpSearchAPI *systemEmpSearchAPI;
@property (nonatomic, strong) NSMutableArray<SAStoreUserModel *> *empMarr;
@property (nonatomic, strong) BubbleTableView *empBubbleView;
@property (nonatomic, strong) BubbleTableView *typeBubbleView;
@property (nonatomic, assign) NSInteger empRow;
@property (nonatomic, assign) NSInteger typeRow;
@property (nonatomic, strong) SAMemberRechargeAPI *memberRechargeAPI;

@property (nonatomic, assign) BOOL isScanPay;
@property (nonatomic, strong) NSString *rechargeOrderId;
@property (nonatomic, strong) NSString *rechargeOrderNo;
@property (nonatomic, strong) SAMemberRechargePayAPI *memberRechargePayAPI;
@property (nonatomic, strong) SAReceiveQueryStatusAPI *receiveQueryStatusAPI;

@property (nonatomic, assign) BOOL isPolling;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;

@property (nonatomic, assign) BOOL isCanPay;
@property (nonatomic, strong) SAGetPayPermissionAPI *getPayPermissionAPI;
@property (nonatomic, strong) UIButton *printBtn;

@end

@implementation SAMemberTopUpVC

-(instancetype)initWithMemberId:(NSString *)memberId MemberName:(NSString *)memberName AndTitle:(NSString *)titleName {
    if (self = [super init]) {
        self.titleName = titleName;
        self.memberId = memberId;
        self.memberName = memberName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemEmpSearchAPI == api) {
        self.empMarr = [SAStoreUserModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (self.empMarr.count > 0) {
            self.empTf.text = self.empMarr[0].empName;
            self.empRow = 0;
        }
    }else if (self.memberRechargeAPI == api) {
        SAPirntTopUpBillModel *billMode = [SAPirntTopUpBillModel new];
        billMode.employees = self.empTf.text;
        billMode.topUp = self.topUpTf.text;
        billMode.giveAway = self.givingTf.text;
        billMode.settlementType = self.typeTf.text;
        billMode.isPrint = self.printBtn.isSelected;
        
        if ([self.typeTf.text isEqualToString:@"扫码收款"]) {
            NSInteger status = [data[@"data"][@"status"] integerValue];
            self.rechargeOrderId = data[@"data"][@"rechargeOrderId"];
            self.rechargeOrderNo = data[@"data"][@"rechargeOrderNo"];
            if (status == 2) {
                !self.refreshBlock ?: self.refreshBlock(billMode);
                [Prompt popPromptViewWithMsg:@"充值成功" duration:2];
                [self.navigationController popViewControllerAnimated:YES];
            }else if (status == 0) {
                [self scanQrcode];
            }
        }else {
            !self.refreshBlock ?: self.refreshBlock(billMode);
            [Prompt popPromptViewWithMsg:@"充值成功" duration:2];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else if (self.memberRechargePayAPI == api) {
        SAPirntTopUpBillModel *billMode = [SAPirntTopUpBillModel new];
        billMode.employees = self.empTf.text;
        billMode.topUp = self.topUpTf.text;
        billMode.giveAway = self.givingTf.text;
        billMode.settlementType = self.typeTf.text;
        billMode.isPrint = self.printBtn.isSelected;
        
        NSInteger status = [data[@"status"] integerValue];
        if (status == 2) {
            !self.refreshBlock ?: self.refreshBlock(billMode);
            [Prompt popPromptViewWithMsg:@"充值成功" duration:2];
            [self.navigationController popViewControllerAnimated:YES];
        }else if (status == 0) {
            self.isPolling = YES;
            self.count = 31;
            [HDHubView loadingMessage:@"正在查询支付状态..."];
            self.receiveQueryStatusAPI.orderNo = self.rechargeOrderNo;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        }else {
            [Prompt popPromptViewWithMsg:@"充值失败" duration:2];
        }
    }else if (self.receiveQueryStatusAPI == api) {
        SAPirntTopUpBillModel *billMode = [SAPirntTopUpBillModel new];
        billMode.employees = self.empTf.text;
        billMode.topUp = self.topUpTf.text;
        billMode.giveAway = self.givingTf.text;
        billMode.settlementType = self.typeTf.text;
        billMode.isPrint = self.printBtn.isSelected;
        
        if (self.isPolling == YES) {
            NSInteger status = [data[@"data"][@"status"] integerValue];
            if (status == 2) {
                self.isPolling = NO;
                [self.timer invalidate];
                self.timer = nil;
                [HDHubView dismissLoading];
                !self.refreshBlock ?: self.refreshBlock(billMode);
                [Prompt popPromptViewWithMsg:@"充值成功" duration:2];
                [self.navigationController popViewControllerAnimated:YES];
            }else if (status == 6 || status == 8) {
                self.isPolling = NO;
                [self.timer invalidate];
                self.timer = nil;
                [HDHubView dismissLoading];
                [Prompt popPromptViewWithMsg:@"充值失败" duration:2];
            }
        }
    }else if (self.getPayPermissionAPI == api) {
        NSString *isCanPayStr = [NSString stringWithFormat:@"%@",data[@"data"]];
        if ([isCanPayStr isEqualToString:@"0"]) {
            self.isCanPay = NO;
        }else {
            self.isCanPay = YES;
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            self.isPolling = NO;
            [self.timer invalidate];
            self.timer = nil;
            [HDHubView dismissLoading];
            NSDictionary *dic = error.userInfo;
            NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [self tipAlertView:msg];
        }
    }else if (self.memberRechargePayAPI == api) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        [self tipAlertView:msg];
    }else if (self.getPayPermissionAPI == api) {
        self.isCanPay = NO;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        return YES;
    }
    if (self.topUpTf == textField || self.typeTf == textField) {
        if (textField.text.length > 7) {
            return NO;
        }
        if (textField.text.length > 0) {
            if ([string isEqualToString:@"-"]) {
                return NO;
            }
        }
        // 如果第一位是.则前面加上0.
        if((textField.text.length == 0) && [string isEqualToString:@"."]) {
            textField.text = @"0";
        }
        if([textField.text containsString:@"."]) {
            if ([string isEqualToString:@"."]) {
                return NO;
            }
            NSRange ran = [textField.text rangeOfString:@"."];
            if(range.location > ran.location) {
                if([textField.text pathExtension].length > 1) {
                    return NO;
                }
            }
        }
        return [self validateNumber:string];
    }
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"-.0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

#pragma mark - event
-(void)clickedEmpBtn {
    if (self.empMarr.count == 0) {
        [Prompt popPromptViewWithMsg:@"请先选择店员" duration:2];
        return;;
    }
    NSMutableArray *marr = [NSMutableArray array];
    for (SAStoreUserModel *model in self.empMarr) {
        if (model.empName.length == 0) {
            model.empName = @"";
        }
        [marr addObject:model.empName];
    }
    NSInteger height = self.empMarr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.empBubbleView) {
        self.empBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:100 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.empRow = row;
            self.empTf.text = rowString;
        } hideBlock:^{
            self.empBubbleView = nil;
        }];
        
        [self.empBubbleView showWithTargetView:self.empBtn maskSuperView:window];
        [self.empBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.empBubbleView.selectRow = self.empRow;
        self.empBubbleView.bubbleCellHeight = 50;
        self.empBubbleView.isBubbleScrollEnabled = YES;
        self.empBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

//充值方式
-(void)clickedTypeBtn {
//    NSArray *marr = @[@"现金", @"刷卡", @"微信", @"支付宝"];
    [self.view endEditing:YES];
    NSArray *marr = @[@"扫码收款" ,@"现金", @"刷卡", @"微信", @"支付宝"];
    BOOL scan = [[SAValueManger shareInStance].userInfo.auditStatus isEqualToString:@"1"];
    BOOL isPayChannel = ![[SAValueManger shareInStance].userInfo.payChannel isEqualToString:@"2"];
    if (scan == YES) {
        scan = isPayChannel;
    }
    if (scan == NO) {
        marr = @[@"现金", @"刷卡", @"微信", @"支付宝"];
    }
    if (self.isCanPay == NO) {
        marr = @[@"现金", @"刷卡", @"微信", @"支付宝"];
    }
    if ([self.topUpTf.text doubleValue] < 0) {
        marr = @[@"现金", @"刷卡", @"微信", @"支付宝"];
    }
    NSInteger height = marr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.typeBubbleView) {
        self.typeBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:100 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.typeRow = row;
            self.typeTf.text = rowString;
        } hideBlock:^{
            self.typeBubbleView = nil;
        }];
        
        [self.typeBubbleView showWithTargetView:self.typeBtn maskSuperView:window];
        [self.typeBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.typeBubbleView.selectRow = self.typeRow;
        self.typeBubbleView.bubbleCellHeight = 50;
        self.typeBubbleView.isBubbleScrollEnabled = YES;
        self.typeBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

-(void)clickedCompleteBtn {
    if (trimString(self.topUpTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"充值金额不能为空" duration:2];
        return;
    }else if (trimString(self.empTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"店员不能为空" duration:2];
        return;
    }else if (trimString(self.typeTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"充值方式不能为空" duration:2];
        return;
    }
    self.memberRechargeAPI.amount = [NSString stringWithFormat:@"%0.lf",[self.topUpTf.text doubleValue] * 100];
    self.memberRechargeAPI.deviceId = kDeviceId;
    self.memberRechargeAPI.empType = self.empMarr[self.empRow].empType;
    self.memberRechargeAPI.givenAmount = [NSString stringWithFormat:@"%0.lf",[self.givingTf.text doubleValue] * 100];
    self.memberRechargeAPI.empId = self.empMarr[self.empRow].empId;
    self.memberRechargeAPI.mobile = self.empMarr[self.empRow].mobile;
    self.memberRechargeAPI.memberId = self.memberId;
    self.memberRechargeAPI.memberName = self.memberName;
    if ([self.typeTf.text isEqualToString:@"现金"]) {
        self.memberRechargeAPI.rechargeType = @"1";
    }else if ([self.typeTf.text isEqualToString:@"刷卡"]) {
        self.memberRechargeAPI.rechargeType = @"2";
    }else if ([self.typeTf.text isEqualToString:@"微信"]) {
        self.memberRechargeAPI.rechargeType = @"4";
    }else if ([self.typeTf.text isEqualToString:@"支付宝"]) {
        self.memberRechargeAPI.rechargeType = @"5";
    }else if ([self.typeTf.text isEqualToString:@"扫码收款"]) {
        self.memberRechargeAPI.rechargeType = @"7";
    }
    [self.memberRechargeAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)scanQrcode {
    WeakSelf
    __block NSString *rechargeOrderId = self.rechargeOrderId;
    __block NSString *rechargeOrderNo = self.rechargeOrderNo;
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:weixinStyle qrResultCallBack:^(id result) {
        weakSelf.memberRechargePayAPI.authCode = result;
        weakSelf.memberRechargePayAPI.rechargeOrderId = rechargeOrderId;
        weakSelf.memberRechargePayAPI.rechargeOrderNo = rechargeOrderNo;
        [weakSelf.memberRechargePayAPI sendRequestToServerWithActivityViewAndMask:POST];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}


- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
        [self.receiveQueryStatusAPI sendRequestToServerWithType:POST];
    } else {
        self.isPolling = NO;
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
        [HDHubView dismissLoading];
    }
}

-(void)tipAlertView:(NSString *)msg {
    GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:msg knowBtnBlock:^(UIButton *knowBtn) {
        [knowBtn setTitle:@"重试" forState:UIControlStateNormal];
        [knowBtn addTarget:self action:@selector(continuePay) forControlEvents:UIControlEventTouchUpInside];
    }];
    [alertView showWithAnimation];
}

-(void)continuePay {
    [self scanQrcode];
}

-(void)clickedPrintBtn:(UIButton *)sender {
    sender.selected = !sender.isSelected;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"会员充值"];
    self.view.backgroundColor = kBgColor;
    
    UILabel *balanceLab = [[UILabel alloc] initWithFrame:SARectMake(26, StatusHeight, 340, 30)];
    balanceLab.textColor = kBlackColor;
    balanceLab.font = kFont(15);
    balanceLab.textAlignment = NSTextAlignmentLeft;
    balanceLab.text = [NSString stringWithFormat:@"可用余额:%0.2lf", [self.titleName doubleValue]/100];
    [self.view addSubview:balanceLab];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 30, kBaseScreenWidth, 204)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    NSArray *arr = @[@"*充值金额", @"赠送金额", @"*选择店员", @"*充值方式"];
    NSArray *arr2 = @[@"请输入充值金额", @"请输入赠送金额", @"请选择店员", @"请选择充值方式"];
    for (int i = 0; i < arr.count; i++) {
        UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(20, 41 * i, 80, 40)];
        titleLab.text = arr[i];
        titleLab.textColor = kBlackColor;
        titleLab.font = kFont(15);
        [whiteView addSubview:titleLab];
        [titleLab setAttributedStringWithSubString:@"*" color:[UIColor redColor]];
        
        UITextField *inputTf = [[UITextField alloc] initWithFrame:SARectMake(150, 41 * i, 185, 40)];
        inputTf.textColor = kBlackColor;
        inputTf.font = kFont(15);
        inputTf.delegate = self;
        inputTf.textAlignment = NSTextAlignmentLeft;
        inputTf.placeholder = arr2[i];
        inputTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        [whiteView addSubview:inputTf];
        
        if (i == 2 || i == 3) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = SARectMake(335, 41 * i, 38, 40);
            [button setImage:[UIImage imageNamed:@"shop_grayAllow"] forState:UIControlStateNormal];
            [whiteView addSubview:button];
            inputTf.clearButtonMode = UITextFieldViewModeNever;
            inputTf.userInteractionEnabled = NO;
            button.userInteractionEnabled = NO;
            
            UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
            button2.frame = SARectMake(0, 41 * i, kBaseScreenWidth, 40);
            [whiteView addSubview:button2];
            
            if (i == 2) {
                [button2 addTarget:self action:@selector(clickedEmpBtn) forControlEvents:UIControlEventTouchUpInside];
                self.empBtn = button;
            }else if (i == 3) {
                [button2 addTarget:self action:@selector(clickedTypeBtn) forControlEvents:UIControlEventTouchUpInside];
                self.typeBtn = button;
            }
        }

        UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 40 + 41 * i, kBaseScreenWidth, 1)];
        line.backgroundColor = kBgColor;
        [whiteView addSubview:line];
        
        if (i == 0) {
            self.topUpTf = inputTf;
            inputTf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }else if (i == 1) {
            self.givingTf = inputTf;
            inputTf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }else if (i == 2) {
            self.empTf = inputTf;
        }else if (i == 3) {
            self.typeTf = inputTf;
        }
    }
    
    
    UILabel *printLab = [[UILabel alloc] initWithFrame:SARectMake(20, 164, 80, 40)];
    printLab.text = @"打印单据";
    printLab.textColor = kBlackColor;
    printLab.font = kFont(15);
    [whiteView addSubview:printLab];
    
    UIButton *printBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    printBtn.frame = SARectMake(140, 164, 40, 40);
    [printBtn setImage:[UIImage imageNamed:@"print_check_n"] forState:UIControlStateNormal];
    [printBtn setImage:[UIImage imageNamed:@"print_check_s"] forState:UIControlStateSelected];
    [printBtn addTarget:self action:@selector(clickedPrintBtn:) forControlEvents:UIControlEventTouchUpInside];
    printBtn.selected = YES;
    [whiteView addSubview:printBtn];
    
    UIButton *completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    completeBtn.frame = SARectMake(70, StatusHeight + 288, 235, 35);
    [completeBtn setTitle:@"充值" forState:UIControlStateNormal];
    [completeBtn setBackgroundImage:[UIImage imageNamed:@"pink_btnBg"] forState:UIControlStateNormal];
    completeBtn.titleLabel.font = kFont(18);
    [completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [completeBtn addTarget:self action:@selector(clickedCompleteBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:completeBtn];
    
    self.empRow = -1;
    self.typeRow = -1;
    [self.systemEmpSearchAPI sendRequestToServerWithActivityViewAndMask:GET];
    [self.getPayPermissionAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(SASystemEmpSearchAPI *)systemEmpSearchAPI {
    if (!_systemEmpSearchAPI) {
        _systemEmpSearchAPI = [SASystemEmpSearchAPI apiWithDelegate:self];
    }
    return _systemEmpSearchAPI;
}

-(NSMutableArray<SAStoreUserModel *> *)empMarr {
    if (!_empMarr) {
        _empMarr = [NSMutableArray array];
    }
    return _empMarr;
}

-(SAMemberRechargeAPI *)memberRechargeAPI {
    if (!_memberRechargeAPI) {
        _memberRechargeAPI = [SAMemberRechargeAPI apiWithDelegate:self];
    }
    return _memberRechargeAPI;
}

-(SAMemberRechargePayAPI *)memberRechargePayAPI {
    if (!_memberRechargePayAPI) {
        _memberRechargePayAPI = [SAMemberRechargePayAPI apiWithDelegate:self];
        _memberRechargePayAPI.isPromptErrorMessage = NO;
    }
    return _memberRechargePayAPI;
}

-(SAReceiveQueryStatusAPI *)receiveQueryStatusAPI {
    if (!_receiveQueryStatusAPI) {
        _receiveQueryStatusAPI = [SAReceiveQueryStatusAPI apiWithDelegate:self];
        _receiveQueryStatusAPI.isPromptErrorMessage = NO;
    }
    return _receiveQueryStatusAPI;
}

-(SAGetPayPermissionAPI *)getPayPermissionAPI {
    if (!_getPayPermissionAPI) {
        _getPayPermissionAPI = [SAGetPayPermissionAPI apiWithDelegate:self];
    }
    return _getPayPermissionAPI;
}

@end
